//
//  chatViewController.m
//  TT
//
//  Created by lanou3g on 16/3/11.
//  Copyright © 2016年 Super磊. All rights reserved.
//

#import "chatViewController.h"
#import "ChatTableViewCell.h"
#import <EMChatManagerDelegate.h>
#import <EaseMob.h>

@interface chatViewController ()<EMChatManagerDelegate,UITextFieldDelegate>
{
    
    EMConversation *conversation;
   
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *top;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sendTop;


@property (weak, nonatomic) IBOutlet UITableView *tableV;
@property (weak, nonatomic) IBOutlet UITextField *textfieldSend;
@property (strong, nonatomic) NSMutableArray *array;
//@property (nonatomic, strong) UITextView *textview;
@end

@implementation chatViewController

@synthesize userName = userName;
- (void)viewDidLoad {
    [super viewDidLoad];
   
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
   
//    新建会话/获取会话列表
    conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:@"22" conversationType:eConversationTypeChat];
//    
    [self.view addSubview:self.textfieldSend];
    [self.view addSubview:self.tableV];
    [self.tableV registerNib:[UINib nibWithNibName:@"ChatTableViewCell" bundle:nil] forCellReuseIdentifier:@"chat_cell"];
    
    self.tableV.estimatedRowHeight = 2;
    self.tableV.rowHeight = UITableViewAutomaticDimension;
    self.textfieldSend.delegate = self;
    [self setData];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
}
- (void)setData {
    [self.array addObject:@"1"];
    [self.array addObject:@"22222222222222222222222222222222222222222222222222222222222222222222222222222"];
    [self.array addObject:@"1"];
    [self.array addObject:@"1"];
    [self.array addObject:@"22222222222222222222222222222222222222222222222222222222222222222222222222222"];
    [self.array addObject:@"1"];
    [self.tableV reloadData];
}
- (void)tapAction {
    [self.textfieldSend resignFirstResponder];
}
#pragma mark 未知
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (IBAction)send:(UIButton *)sender {
    //    发送的文本信息
    EMChatText *textChat = [[EMChatText alloc]initWithText:self.textfieldSend.text];
    //    聊天的文本消息体对象
    EMTextMessageBody *body = [[EMTextMessageBody alloc]initWithChatObject:textChat];
    EMMessage *message = [[EMMessage alloc]initWithReceiver:@"22" bodies:@[body]];
    //    单聊信息
    message.messageType = eMessageTypeChat;
    EMError *error = nil;
    
    id<IChatManager> chatManager = [[EaseMob sharedInstance]chatManager];
    [chatManager sendMessage:message progress:nil error:&error];
    
    if (error) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"消息发送失败" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"重新发送" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [chatManager resendMessage:message progress:nil error:nil];
        }];
        [alert addAction:action];
        [alert addAction:action1];
        [self presentViewController:alert animated:YES completion:nil];

    [self.tableV reloadData];
   }

}

#pragma mark 键盘控制
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [UIView animateWithDuration:1 animations:^{
        self.sendTop.constant = 350;
        self.top.constant = 350;
        
    }];
    return YES;
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    [UIView animateWithDuration:0.5 animations:^{
        self.sendTop.constant = 500;
        self.top.constant = 500;
    }];
}


/*
-(void)addText{
    EMConversation *conversation2 = [[EaseMob sharedInstance].chatManager conversationForChatter:@"22" conversationType:(eConversationTypeChat)];
    NSString *context = @"";
    NSArray *arrcon;
    NSArray *arr;
    long long timetamp = [[NSDate date]timeIntervalSince1970]*1000+1;
    arr = [conversation2 loadAllMessages];
    arrcon = [conversation2 loadNumbersOfMessages:10 before:timetamp];
    for (EMMessage *he in arrcon) {
        id<IEMMessageBody>messageBody = [he.messageBodies firstObject];
        NSString *messageStr = nil;
        messageStr = ((EMTextMessageBody *)messageBody).text;
        if (![he.from isEqualToString:@"22"]) {
            context = [NSString stringWithFormat:@"%@\n\tttttt%@",context,messageStr];
        }else{
            context = [NSString stringWithFormat:@"%@\n%@",context,messageStr];
        }
    }
    
}

*/
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.array.count;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

#pragma mark 涉及到重用！！！！
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatTableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:@"chat_cell" forIndexPath:indexPath];

    if ([self.array[indexPath.row] isEqualToString:@"1"]) {
        cell.leftImageV.hidden = YES;
        cell.leftLable.hidden = YES;
        cell.rightLable.text = self.array[indexPath.row];
        cell.rightImageV.backgroundColor = [UIColor yellowColor];
    } else {
        cell.rightImageV.hidden = YES;
        cell.rightLable.hidden = YES;
        cell.leftLable.text = self.array[indexPath.row];
        cell.leftImageV.backgroundColor = [UIColor yellowColor];
    }
    return cell;
}


-(void)didReceiveMessage:(EMMessage *)message{
    id<IEMMessageBody>messageBody = [message.messageBodies firstObject];
    NSString *messageStr = nil;
    messageStr = ((EMTextMessageBody *)messageBody).text;
    [self.array addObject:messageStr];
    [self.tableV reloadData];
}

- (NSMutableArray *)array {
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
